package com.nurt.controller.dish;

import com.nurt.dto.ResultDto;
import com.nurt.entity.DishEntity;
import com.nurt.service.DishService;
import com.nurt.service.impl.DishServiceImpl;
import com.nurt.utils.ServletHelper;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.util.List;

@WebServlet("/dishes/*")
public class DishController extends HttpServlet {
    private DishService dishService;

    public void init() {
        dishService = new DishServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pathInfo = req.getPathInfo();
        if (pathInfo == null || pathInfo.equals("/")) {
            List<DishEntity> dishes = dishService.getDishes();
            resp.getWriter().write(ResultDto.success(dishes));        
        } else {
            // getDish
            String dishId = pathInfo.substring(1);
            DishEntity dish = dishService.getDish(Integer.parseInt(dishId));
            resp.getWriter().write(ResultDto.success(dish));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // createDish
        DishEntity newDish = ServletHelper.getRequestBodyAsObject(req, DishEntity.class);
        int dishId = dishService.addDish(newDish);
        resp.getWriter().write(ResultDto.success(dishId));
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // updateDish
        String dishIdStr = req.getPathInfo().substring(1);
        int dishId = Integer.parseInt(dishIdStr);
        DishEntity dish = ServletHelper.getRequestBodyAsObject(req, DishEntity.class);
        dish.setDishId(dishId);
        dishService.updateDish(dish);
        resp.getWriter().write(ResultDto.success(dish));
    }
}